package com.max.common.proxy;

import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 
 * 项目名称:max-project-graphics
 * 文件名称:LocalPorxyHandler.java
 * 文件描述:
 * 创建人员:chenyibo
 * 创建时间:2013-1-22 下午02:58:01
 * 修改人员:chenyibo
 * 修改时间:2013-1-22 下午02:58:01
 * 修改备注:
 * @version V1.0
 */
@SuppressWarnings("serial")
public class LocalPorxyHandler implements InvocationHandler, Serializable
{
	private static Log log = LogFactory.getLog("proxy");
	
	private static Map<Class<?>,Object> map = null;
	
	private Class<?> clazz = null;
	
	
	public LocalPorxyHandler(Class<?> _type) 
	{
		this.clazz = _type;
	}


	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable 
	{
		String local_ip = "127.0.0.1";
		String remote_ip = "127.0.0.1";
		String module = "-";
		String function = "-";
		int ret = 0;
		long time = System.currentTimeMillis();
		String remark = "success!";
		
		try
		{
			Object obj = null;
			
			if (clazz.isAnnotationPresent(Proxy.class))
			{
				Proxy config = clazz.getAnnotation(Proxy.class);
				String strclazz = config.clazz();
				boolean singleton = config.singleton();
				
				if(singleton)
				{
					if(map == null)
						map = new HashMap<Class<?>,Object>();
					
					if(!map.containsKey(clazz))
					{
						obj = Class.forName(strclazz).newInstance();
						map.put(clazz, obj);
					}
					else
						obj = map.get(clazz);
				}
				else
					obj = Class.forName(strclazz).newInstance();
			}
			
			return method.invoke(obj, args);
		}
		catch(Throwable t)
		{
			ret = -1;
			remark = t.getMessage();
			throw t;
		}
		finally
		{
			module = clazz.getSimpleName();
			function = method.getName();
			time = System.currentTimeMillis()-time;
			
			StringBuffer sb = new StringBuffer();
			sb.append(local_ip).append("\t")
			  .append(remote_ip).append("\t")
			  .append(module).append("\t")
			  .append(function).append("\t")
			  .append(ret).append("\t")
			  .append(time).append("\t")
			  .append(remark);
			log.info(sb.toString());
		}
	}
}
